package good;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;

import BookModel.Book;
import BookModel.Inventory;
import BookModel.Year;
import au.com.bytecode.opencsv.CSVReader;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class WithAttrib {
	public static void main(String[] args) throws FileNotFoundException,
			IOException {

		final String CSV_FILE = "books.csv";
		CSVReader reader = new CSVReader(new FileReader(CSV_FILE));
		String[] nextLine;
		Inventory inventory = new Inventory();
		//List<Book> bookList = new ArrayList<Book>();
		XStream xStream = new XStream(new DomDriver());
		
		while ((nextLine = reader.readNext()) != null) {

			Book book = new Book();
			book.setYear(new Year(nextLine[0]));
			book.setAuthor(nextLine[2]);
			book.setIsbn(nextLine[4]);
			book.setPrice(nextLine[5]);
			book.setPublisher(nextLine[3]);
			book.setTitle(nextLine[1]);

			inventory.addBook(book);

			xStream.alias("inventory", Inventory.class);
			xStream.alias("book", Book.class);
			xStream.useAttributeFor(Book.class, "year");
			xStream.registerConverter(new YearConverter());
			xStream.addImplicitCollection(Inventory.class, "bookList");

			try {
				BufferedWriter out = new BufferedWriter(new FileWriter("generated.xml"));
				Iterator<Book> iter = inventory.getBookList().iterator();
				while (iter.hasNext()) {
					out.write(xStream.toXML(iter.next()));
					out.write("\n");
				}
				out.close();
			} catch (IOException e) {
			}
		}
		System.out.println(xStream.toXML(inventory));
	}
}

